import axios from 'axios'
import router from '@/router';

import { MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'
import qs from 'qs';
// 根据环境不同引入不同api地址
import { baseUrl } from '@/config'


// create an axios instance
const service = axios.create({
  baseURL: baseUrl, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

let GolbalLoading = null;

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      // GolbalLoading = Loading.service({
      //   text: '加载中'
      // })
    }
    if (store.getters.token) {
      config.headers['Authorization'] = store.getters.token?store.getters.token:''
    }
    if(config.method == 'post') {
      // config.data = qs.stringify(config.data)  
      // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    } else { 
        // config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    }
    return config
  },
  error => {
    if(GolbalLoading){
      GolbalLoading.close();
    }
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if(GolbalLoading){
      GolbalLoading.close();
    }
    const res = response.data
    if(response.status === 200){//请求正常
      if(res.status === 0){
        return Promise.resolve(res.data)
      }else if(res.status === 401){
        router.push({
          path: '/login'
      })
        store.commit('user/RESET_STATE')
        return Promise.reject(res.message || "Error")
      }else{
        MessageBox({
          title:'提示',
          message:res.message||"请求错误",
          type: 'warning'
        }).then(() => {
          // 重置
          // store.dispatch('user/RESET_STATE').then(() => {
          //   location.reload()
          // })
        })
        return Promise.reject(new Error(res.message || 'Error'))
      }
    }else{
        Message({
          message: response.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    if(GolbalLoading){
      GolbalLoading.close();
    }
    // console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)


export default service
